import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import renderModal, {
    getModelValue,
    initModelValue,
    renderForm,
    type FormModalDto
} from '@/components/modal/Modal'
import type { FilterDto } from '@/render/FilterRender'
import { ProductTypeEnum } from '@/const/enum'
import { addContact, editContact } from '@/api/deal'
import type { SaleReqDto } from '@/api/deal/types'
import type { CompanyInfoDto, PeriodInfoReqDto, WesureInfoDto } from '@/api/company/types'
import { updateSaasCompany } from '@/api/company'
import { confirm, getReceiptData } from '@/utils/util'
import DialogRecharge from './DialogRecharge'
import { getDaliyInsuranceSolutionList } from '@/api/insurance/daily'
import type { DictionaryDto } from '@/api/types'
import { Button, message, Tag } from 'ant-design-vue'
import dayjs from 'dayjs'

@Component({
    expose: ['getData']
})
export class AccountDetailView extends Render {
    @Prop() basicData!: WesureInfoDto
    @Prop() companyBasicInfo!: CompanyInfoDto

    showRecharge = false

    get periodCompanyTypeListValue() {
        const data = getModelValue(this.basicFormConfig)
        return data.periodCompanyTypeList
    }

    @Emit('refresh')
    handleRefresh() {}

    @Watch('basicData')
    async handleWatch() {
        if (this.basicData.channelId) {
            this.basicFormConfig.items.receiptId.options = await getReceiptData(
                this.basicData.channelId
            )
        }

        // 整理后端给的投保方案
        if (this.basicData.insureType) {
            this.basicData.insureTypeList = JSON.parse(this.basicData.insureType).map(
                (i: DictionaryDto) => {
                    return i.dictValue
                }
            )
        }
        // 根据 保险公司获取投保方案列表
        if (this.basicData.insureCompanyType) {
            this.basicFormConfig.items.insureTypeList.options = await this.insureTypeList(
                this.basicData.insureCompanyType
            )
        }

        if (this.basicData.isOpenWesure) {
            initModelValue(this.basicFormConfig, this.basicData)
        }
    }

    basicFormConfig = this.initFormConfig() as FormModalDto
    initFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                insureCompanyType: {
                    name: '保险公司',
                    element: 'select',
                    optionsType: 'daliyInsuranceCompany',
                    params: {
                        clearable: false
                    },
                    required: true,
                    callback: {
                        change: async (value: string) => {
                            this.basicFormConfig.items.insureTypeList.value = []
                            this.basicFormConfig.items.insureTypeList.options = value
                                ? await this.insureTypeList(value)
                                : []
                        }
                    }
                },
                insureTypeList: {
                    name: '投保方案',
                    element: 'select',
                    params: {
                        clearable: false
                    },
                    multiple: true,
                    required: true
                },
                saleId: {
                    name: '所属销售',
                    element: 'select',
                    optionsType: 'saleList',
                    required: true
                },
                channelId: {
                    name: '收款渠道',
                    element: 'select',
                    optionsType: 'channel',
                    required: true,
                    callback: {
                        change: async (value: number) => {
                            this.basicFormConfig.items.receiptId.value = ''
                            if (value) {
                                this.basicFormConfig.items.receiptId.options =
                                    await getReceiptData(value)
                            } else {
                                this.basicFormConfig.items.receiptId.options = []
                            }
                        }
                    }
                },
                receiptId: {
                    name: '收款账号',
                    element: 'select',
                    required: true
                }
            },
            complete: async () => {
                const data = getModelValue(this.basicFormConfig)
                console.log(1234, data)
                // await updatePayManagerUser(data)
                message.success('更新成功')
                this.basicFormConfig.show = false
            },
            cancel: () => {
                this.basicFormConfig.show = false
            },
            init: () => {}
        } as FormModalDto
    }
    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    filterBtnConfig() {
        return {} as FilterDto
    }

    async insureTypeList(insureCompany: string) {
        return (
            await getDaliyInsuranceSolutionList({
                insureCompany
            })
        ).map((item) => {
            item.label = item.dictLabel
            item.value = item.dictValue
            return item
        })
    }

    async onSubmit() {
        await this.basicForm.validate()
        await confirm('确认修改吗？', '提示', {
            type: 'warning'
        })
        const params = getModelValue(this.basicFormConfig) as PeriodInfoReqDto
        params.area = this.companyBasicInfo.area
        params.auditStatus = 1
        params.companyName = this.companyBasicInfo.companyName
        params.creditCode = this.companyBasicInfo.creditCode
        params.id = this.companyBasicInfo.companyId
        params.isOpenWesure = 1
        params.legalPerson = this.companyBasicInfo.legalPerson
        params.merchantBankCard = this.companyBasicInfo.merchantBankCard
        params.productType = ProductTypeEnum.DALIY

        const saleParams = {
            companyId: this.basicData.companyId,
            id: this.basicData.dealId,
            productType: ProductTypeEnum.PAYWAGE,
            saleId: params.saleId,
            serviceStartTime: dayjs().startOf('day').format('YYYY-MM-DD'),
            serviceState: 0
        } as SaleReqDto
        delete params.saleId
        await updateSaasCompany(params)
        if (!this.basicData.saleId) {
            await addContact(saleParams)
        } else {
            await editContact({
                ...saleParams,
                saleOldId: this.basicData.saleId
            })
        }
        message.success('更新成功')
        this.handleRefresh()
    }

    onShowRecharge() {
        this.showRecharge = true
        // this.rechargeFormConfig.title = `${this.companyBasicInfo.companyName}子弹发薪充值窗口`
        // this.rechargeFormConfig.show = true
    }

    created() {
        this.basicForm = renderForm(this.basicFormConfig)
    }

    renderStatistics() {
        return <></>
    }

    renderRightBtns() {
        return <></>
    }

    render() {
        return (
            <div class="border-1 border-solid rounded-sm">
                <div class="flex flex-wrap items-center px-20px py-10px border-b-1 border-b-solid">
                    <span class="mr-10px">日日保</span>
                    <Tag color={this.basicData.isOpenWesure ? 'primary' : 'info'} class="mr-10px">
                        {this.basicData.isOpenWesure ? '已开通' : '未开通'}
                    </Tag>
                    {this.basicData.isOpenWesure ? (
                        <span class="text-gray-default mr-10px">
                            {this.basicData.productOpenTime} 开通
                        </span>
                    ) : (
                        <></>
                    )}
                    <Button type="text" class="text-blue-100" onClick={this.onShowRecharge}>
                        充值
                    </Button>
                </div>
                <div class="pt-20px">{this.basicForm.element()}</div>
                <div class="flex justify-center pb-20px mt-20px">
                    <Button type="primary" onClick={this.onSubmit}>
                        {this.basicData.isOpenWesure ? '确定修改' : '确定开通'}
                    </Button>
                </div>
                <DialogRecharge
                    v-model:show={this.showRecharge}
                    basicData={this.basicData}
                    companyBasicInfo={this.companyBasicInfo}
                    onRefresh={this.handleRefresh}
                />
            </div>
        )
    }
}

export default toNative<
    { basicData: WesureInfoDto; companyBasicInfo: CompanyInfoDto },
    { refresh: () => void }
        >(AccountDetailView)
